/**
 * 11选5的共用逻辑
 */
(function() {
    var currTabId = 1;
    var tabDraws = [
        // 1：两面
        fill_zonghe_row,

        // 2 单号
        fill_danhao,

        // 3 连码
        fill_lianma,

        // 4 直选
        fill_zhixuan,
    ];

    // 填充总和
    function fill_zonghe_row() {
        var types = ["大", "单", "尾大", "龙", '小', '双', '尾小', '虎'];
        var table = $(".zonghe tbody");
        table.empty();
        var tr = $("<tr></tr>");
        for (var i = 0; i < types.length; i++) {
            var key = types[i];
            var name = types[i];
            if (key == '大' || key == '小' || key == '单' || key == '双') {
                key = '和' + key;
                name = '总和' + name;
            }
            if (key == '尾大' || key == '尾小') name = '总和' + name;

            add_bet_item(key, name, tr);
            if (i == 3) {
                table.append(tr);
                tr = $("<tr></tr>");
            }
        }
        table.append(tr);

        var ths = ["第一球", "第二球", "第三球", "第四球", "第五球"];
        var arr = ['一', '二', '三', '四', '五'];
        var types = ["大", "小", "单", "双"];
        
        // 1~5球的大小单双
        var div = $(".q1-5 tbody tr");
        div.empty();
        for (var i in arr) {
            var td = $("<td></td>"); div.append(td);
            var table = $('<table class="u-table2 play_tab_30"> </table>'); td.append(table);
            table.append('<thead><tr><th colspan="3">__i__</th></tr></thead>'.replace(/__i__/, ths[i]));
            var tbody = $("<tbody></tbody>"); table.append(tbody);

            for (var j in types) {
                var tr = $("<tr></tr>");
                add_bet_item(arr[i] + types[j], types[j], tr);
                tbody.append(tr);
            }
        }
    }

    function fill_danhao() {
        var ths = ["第一球", "第二球", "第三球", "第四球", "第五球"];
        var arr = ['一', '二', '三', '四', '五'];
        var types = ["大", "小", "单", "双"];
        
        // 一中一
        var table = $(".zhong1 tbody");
        table.empty();
        var tr = $("<tr></tr>");
        for (var i = 1; i <= 15; i++) {
            if (i > 11) {
                tr.append("<td colspan='12'> </td>");
                break;
            }
            var k = i < 10 ? "0" + i : i;
            var title = '<span class="ball c-b1">__i__</span>'.replace(/__i__/, i);
            add_bet_item2("任1:" + i, title, tr);
            if (i % 5 == 0) {
                table.append(tr);
                tr = $("<tr></tr>");
            }
        }
        table.append(tr);

        // 1~5球的数字
        var div = $(".dan-q1-5 ");
        div.empty();
        for (var i in arr) {
            var li = $("<li></li>"); div.append(li);
            var table = $('<table class="u-table2 play_tab_30"> </table>'); li.append(table);
            table.append('<thead><tr><th colspan="3">__i__</th></tr></thead>'.replace(/__i__/, ths[i]));

            for (var j = 1; j <= 11; j++) {
                var tr = $("<tr></tr>");
                var k = j < 10 ? "0" + j : j;
                var title = '<span class="ball c-b1">__i__</span>'.replace(/__i__/, j);
                add_bet_item(arr[i] + k, title, tr);
                table.append(tr);
            }
        }
    }

    /*************处理连码 */
    // 填充连码
    function fill_lianma() {
        // 填充11个号码
        var table = $("#lm_checkboxs");
        table.empty();
        var tr = $("<tr></tr>");
        for (var i = 1; i <= 6; i++) {
            tr.append('<td class="name not-event"><span class="ball c-b1">__i__</span></td>'.replace(/__i__/, i));
            tr.append('<td class="checkbox_td"><input type="checkbox" value="__i__"></td>'.replace(/__i__/, i));
        }
        table.append(tr);
        var tr = $("<tr></tr>");
        for (var i = 7; i <= 11; i++) {
            tr.append('<td class="name not-event"><span class="ball c-b1">__i__</span></td>'.replace(/__i__/, i));
            tr.append('<td class="checkbox_td"><input type="checkbox" value="__i__"></td>'.replace(/__i__/, i));
        }
        tr.append('<td class="name not-event"> </td>');
        tr.append('<td class="checkbox_td"> </td>');
        table.append(tr);

        $("#tab3 .radio_td input[type='radio']").change(function() {
            clear_lianma();
        });
        $("#tab3 .checkbox_td input[type='checkbox']").change(function() {
            refresh_lianma_numbers();
        });
    }

    // 当前的投注类型
    function get_lianma_target() {
        var arr = $("#tab3 .radio_td input:checked");
        if (arr.length == 0) {
            $("#tab3 .radio_td input:first")[0].checked = true;
        }
        return $("#tab3 .radio_td input:checked").attr("value");
    }

    // 取得当前选中的数字列表
    function get_lianma_numbers() {
        var arr = $("#tab3 .checkbox_td input:checked");
        var list = [];
        for (var i = 0; i < arr.length; i++) {
            list.push($(arr[i]).attr("value"))
        }
        return list;
    }

    // 清理选中的数字
    function clear_lianma() {
        var arr = $("#tab3 .checkbox_td input:checked");
        for (var i = 0; i < arr.length; i++) $(arr[i])[0].checked = false;
        refresh_lianma_numbers();
    }

    // 刷新连码的数字信息
    function refresh_lianma_numbers() {
        var arr = $("#tab3 .checkbox_td input");
        var max = parseInt(get_lianma_target()[1]);
        var list = get_lianma_numbers();
        var k = get_lianma_target();
        if (k == '组2' || k == '组3') max = 5;

        arr.attr("disabled", false);
        if (list.length >= max) {
            // 其他数字需要置灰
            for (var i = 0; i < arr.length; i++) {
                if (!arr[i].checked)
                    $(arr[i]).attr('disabled', true);
            }
        }

        for (var i = 0; i < arr.length; i++) {
            if (arr[i].checked) {
                $(arr[i]).parent().attr("class", "checkbox_td bg_yellow");
            }
            else {
                $(arr[i]).parent().attr("class", "checkbox_td");
            }
        }
    }
    /*************处理直选 */
    // 填充直选
    function fill_zhixuan() {
        // 填充11个号码
        for (var z = 1; z <= 3; z++) {
            var table = $("#zx_checkbox_" + z);
            table.empty();
            var tr = $("<tr></tr>");
            for (var i = 1; i <= 6; i++) {
                tr.append('<td class="name not-event"><span class="ball c-b1">__i__</span></td>'.replace(/__i__/, i));
                tr.append('<td class="checkbox_td"><input type="checkbox" value="__i__"></td>'.replace(/__i__/, i));
            }
            table.append(tr);

            var tr = $("<tr></tr>");
            for (var i = 7; i <= 11; i++) {
                tr.append('<td class="name not-event"><span class="ball c-b1">__i__</span></td>'.replace(/__i__/, i));
                tr.append('<td class="checkbox_td"><input type="checkbox" value="__i__"></td>'.replace(/__i__/, i));
            }
            tr.append('<td class="name not-event"></td>');
            tr.append('<td class="checkbox_td"></td>');
            table.append(tr);
        }

        $("#tab4 .radio_td input[type='radio']").change(function() {
            clear_zhixuan();
        });
        $("#tab4 .checkbox_td input[type='checkbox']").change(function() {
            refresh_zhixuan_numbers();
        });
    }

    // 当前的投注类型
    function get_zhixuan_target() {
        var arr = $("#tab4 .radio_td input:checked");
        if (arr.length == 0) {
            $("#tab4 .radio_td input:first")[0].checked = true;
        }
        return $("#tab4 .radio_td input:checked").attr("value");
    }

    // 取得当前选中的数字列表
    function get_zhixuan_numbers(list1, list2, list3) {
        var arr = $("#zx_checkbox_1 .checkbox_td input:checked");
        for (var i = 0; i < arr.length; i++) {
            list1.push($(arr[i]).attr("value"))
        }

        var arr = $("#zx_checkbox_2 .checkbox_td input:checked");
        for (var i = 0; i < arr.length; i++) {
            list2.push($(arr[i]).attr("value"))
        }

        var arr = $("#zx_checkbox_3 .checkbox_td input:checked");
        for (var i = 0; i < arr.length; i++) {
            list3.push($(arr[i]).attr("value"))
        }
    }

    // 清理选中的数字
    function clear_zhixuan() {
        var arr = $("#tab4 .checkbox_td input:checked");
        for (var i = 0; i < arr.length; i++) $(arr[i])[0].checked = false;
        refresh_zhixuan_numbers();

        if (get_zhixuan_target() == '直2')
            $("#zx_table_3").hide();
        else
            $("#zx_table_3").show();
    }

    // 刷新直选的数字信息
    function refresh_zhixuan_numbers() {
        var key = get_zhixuan_target();
        var list1 = [], list2 = [], list3 = [];
        var arr1 = $("#zx_checkbox_1 .checkbox_td input");
        var arr2 = $("#zx_checkbox_2 .checkbox_td input");
        var arr3 = $("#zx_checkbox_3 .checkbox_td input");
        get_zhixuan_numbers(list1, list2, list3);
        
        $("#tab4 .checkbox_td input").attr("disabled", false);
        var f = function(arr, list2, list3, three) {
            for (var i = 0; i < arr.length; i++) {
                var v = $(arr[i]).attr("value");
                if (list2.indexOf(v) != -1) $(arr[i]).attr("disabled", true);
                if (three && list3.indexOf(v) != -1) $(arr[i]).attr("disabled", true);
            }
        };
        f(arr1, list2, list3, key == '直3');
        f(arr2, list1, list3, key == '直3');
        if (key == '直3')
            f(arr3, list1, list2, true);

        var f = function(arr) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i].checked) {
                    $(arr[i]).parent().attr("class", "checkbox_td bg_yellow");
                }
                else {
                    $(arr[i]).parent().attr("class", "checkbox_td");
                }
            }
        }
        f(arr1);
        f(arr2);
        f(arr3);

        if (key == '直2')
            $("#zx_table_3").hide();
        else
            $("#zx_table_3").show();
    }

    var initF = function(game, first) {
        window.game = game;
        initGame(game, function() {
            if (first !== false) fillGameTabs(["两面", "单号", "连码", "直选"]);
            currTabId = parseInt($("#cate_menus_50 .selected").attr("tid"));
            $("#tab" + currTabId).attr("flag", 1);
            var f = tabDraws[currTabId - 1];
            f();
        }, first);
    }

    // 重载确定投注的逻辑
    var getCounterListF = function(f) {
        if ($(".cate_menu a.selected").attr("tid") == 3) {
            // 连码的处理
            var max = parseInt(get_lianma_target()[1]);
            var list = get_lianma_numbers();
            var v = parseInt($("#bet_money1").val());
            if (v < 1 || list.length < max) {
                layer.alert("下注内容不正确，请重新下注", { icon: 2 });
                return;
            }
            var key = get_lianma_target();
            key = key + ":" + list.join(",");
            var data = {};
            data[key] = v * 100;
            return data;
        }
        else if ($(".cate_menu a.selected").attr("tid") == 4) {
            // 直选的处理
            var key = get_zhixuan_target();
            var max = parseInt(key[1]);
            var list1 = [], list2 = [], list3 = [];
            get_zhixuan_numbers(list1, list2, list3);
            var v = parseInt($("#bet_money1").val());
            if (v < 1) {
                layer.alert("下注内容不正确，请重新下注", { icon: 2 });
                return;
            }
            if (key == '直2' && (list1.length < 1 || list2.length < 1) ||
                key == '直3' && (list1.length < 1 || list2.length < 1 || list3.length < 1)) {
                layer.alert("下注内容不正确，请重新下注", { icon: 2 });
                return;
            }

            var data = {};
            if (key == '直2') {
                for (var i in list1) {
                    var n1 = list1[i];
                    for (var j in list2) {
                        var n2 = list2[j];
                        data['直2:' + n1 + ',' + n2] = v * 100;
                    }
                }
            }
            else {
                for (var i in list1) {
                    var n1 = list1[i];
                    for (var j in list2) {
                        var n2 = list2[j];
                        for (var k in list3) {
                            var n3 = list3[k];
                            data['直3:' + n1 + ',' + n2 + ',' + n3] = v * 100;
                        }
                        
                    }
                }
            }
            return data;
        }
        else
            return f();
    }
    var resetF = function(f) {
        if ($(".cate_menu a.selected").attr("tid") == 3) {
            clear_lianma();
        }
        else if ($(".cate_menu a.selected").attr("tid") == 4) {
            clear_zhixuan();
        }  
        else
            return f();
    }

    // 解析名称
    var parseTargetF = function(k) {
        if (k.startsWith('组2')) {
            var arr = k.split(':');
            var numbers = arr[1].split(',');
            var i = 1;
            if (numbers.length == 3) i = 3;
            if (numbers.length == 4) i = 6;
            if (numbers.length == 5) i = 10;
            return '前二组选 ' + arr[1] + ' [' + i + '组]';
        }
        if (k.startsWith('组3')) {
            var arr = k.split(':');
            var numbers = arr[1].split(',');
            var i = 1;
            if (numbers.length == 4) i = 4;
            if (numbers.length == 5) i = 10;
            return '前三组选 ' + arr[1] + ' [' + i + '组]';
        }
        return gameRule.getTargetName(k);
    }

    // 计算列表
    var calcBetF = function(data) {
        var total = 0, count = 0;
        for (var k in data) {
            if (k.startsWith('组2')) {
                var arr = k.split(':');
                var numbers = arr[1].split(',');
                var i = 1;
                if (numbers.length == 3) i = 3;
                if (numbers.length == 4) i = 6;
                if (numbers.length == 5) i = 10;
                count += i;
                total += data[k] * i;
                continue;
            }
            if (k.startsWith('组3')) {
                var arr = k.split(':');
                var numbers = arr[1].split(',');
                var i = 1;
                if (numbers.length == 4) i = 4;
                if (numbers.length == 5) i = 10;
                count += i;
                total += data[k] * i;
                continue;
            }
            count++;
            total += data[k];
        }
        return [count, total];
    }

    var unpackF = function(data) {
        // 将组2和组3展开
        var r = {};
        for (var k in data) {
            if (k.startsWith('组2')) {
                var arr = k.split(':');
                var numbers = arr[1].split(',');
                var list = group2(numbers);
                for (var i in list) {
                    r['组2:' + list[i].join(',')] = data[k];
                }
                r.group = '前二组选 ' + arr[1] + '[' + list.length + '组]_' + get_server_time();
            }
            else if (k.startsWith('组3')) {
                var arr = k.split(':');
                var numbers = arr[1].split(',');
                var list = group3(numbers);
                for (var i in list) {
                    r['组3:' + list[i].join(',')] = data[k];
                }
                r.group = '前三组选 ' + arr[1] + '[' + list.length + '组]_' + get_server_time();
            }
            else
                r[k] = data[k];
        }
        return r;
    }

    // 检测能否下注，看下单号1-10是否满足要求
    var checkF = function(type, issue, data) {
        if (type != 'gd115' && type != 'zy115') return true;

        var limit = Util.getNumberLimit(type);
        if (limit <= 0 || limit >= 10) return true;

        var arr1 = ['一', '二', '三', '四', '五'];
        var arr2 = ['01', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11'];
        var m = {};
        for (var k in data) {
            if (k.length != 3) continue;
            var k1 = k[0], k2 = k.substring(1);
            if (arr1.indexOf(k1) != -1 && arr2.indexOf(k2) != -1) {
                if (!m[k1]) m[k1] = {};
                m[k1][k2] = true;
            }
        }
        if (Util.isEmpty(m)) return true;

        // 获取下已经下注的单据
        var bets = context.bets[type];
        if (bets) bets = bets[issue] || [];
        else bets = [];
        for (var i in bets) {
            var k = bets[i].target;
            if (k.length != 3) continue;
            var k1 = k[0], k2 = k.substring(1);
            if (arr1.indexOf(k1) != -1 && arr2.indexOf(k2) != -1) {
                if (!m[k1]) m[k1] = {};
                m[k1][k2] = true;
            }
        }

        var total = 0;

        for (var k in m) {
            var m2 = m[k];
            if (Object.keys(m2).length > limit) {
                var l = "下注失败，__g__ 定位玩法，单个名次不允许下注__v__码或者__v__以上！如有疑问，请咨询客服！";
                l = l.replace(/__g__/, get_game_display_name(type));
                l = l.replace(/__v__/g, limit);
                alert2(l, true);
                return false;
            }
        }

        return true;
    }

    var drawF = function(list) {
        var div = $("#result_balls");
        div.attr("class", "T_KLSF L_GDKLSF");
        var l = '<span><b class="b__index__"></b></span>';
        for (var i in list) {
            var s = l.replace(/__index__/g, list[i]);
            div.append(s);
        }
    }
    var data = {
        drawResult: drawF,
        checkBetList: checkF,
        unpack: unpackF,
        parseTarget: parseTargetF,
        calcBetList: calcBetF,
        getCounterList: getCounterListF,
        reset: resetF,
        init: initF,
    }
    context.global.game["gd115"] = data;
    context.global.game["zy115"] = data;
})();
